<template>
  <div class="roles">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <hr>
    <el-button type="success" plain @click="isShowAddDialog=true">添加角色</el-button>
    <!-- 添加对话框 -->
    <el-dialog title="添加角色" :visible.sync="isShowAddDialog">
      <el-form :model="addForm" :rules="editFormRules" ref="addForm" status-icon label-width="100px">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="addForm.roleName" autocomplete="off" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" autocomplete="off" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowAddDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </div>
    </el-dialog>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="roles">
          <p v-if="roles.row.children.length === 0">暂无权限</p>
          <el-row v-for="item1 in roles.row.children" :key="item1.id" class="border-bottom">
            <el-col :span="4">
              <el-tag closable :disable-transitions="false" @close="handleClose(roles.row, item1.id)">{{ item1.authName }}</el-tag>
              <i class="el-icon-arrow-right"></i>
            </el-col>
            <el-col :span="20">
              <el-row  v-for="item2 in item1.children" :key="item2.id">
                <el-col :span="4">
                  <el-tag closable type="success" @close="handleClose(roles.row, item2.id)">{{ item2.authName }}</el-tag>
                  <i class="el-icon-arrow-right"></i>
                </el-col>
                <el-col :span="20">
                  <el-tag closable type="warning" v-for="item3 in item2.children" :key="item3.id" @close="handleClose(roles.row, item3.id)">添加商品</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="#" type="index" width="50">
      </el-table-column>
      <el-table-column label="角色名" prop="roleName">
      </el-table-column>
      <el-table-column label="角色描述" prop="roleDesc">
      </el-table-column>
      <el-table-column label="操作" prop="option">
        <template slot-scope="roleInfo">
          <el-button @click="showEditDialog(roleInfo.row)" plain type="primary">编辑</el-button>
          <!-- 修改角色对话框 -->
          <el-dialog title="修改角色" :visible.sync="isShowEditDialog">
            <el-form :model="editForm" :rules="editFormRules" ref="editForm" status-icon label-width="100px">
              <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
                <el-input v-model="editForm.roleName" autocomplete="off" placeholder="请输入角色名称"></el-input>
              </el-form-item>
              <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
                <el-input v-model="editForm.roleDesc" autocomplete="off" placeholder="请输入角色描述"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="isShowEditDialog = false">取 消</el-button>
              <el-button type="primary" @click="editRoles">确 定</el-button>
            </div>
          </el-dialog>
          <el-button type="danger" plain @click="del(roleInfo.row)">删除</el-button>
          <el-button type="success" plain @click="showRightDialog(roleInfo.row)">分配角色</el-button>
          <el-dialog title="收货地址" :visible.sync="isShowRightDialog">
            <el-tree
            :data="allRights"
            show-checkbox
            node-key="id"
            ref="tree"
            :default-checked-keys="currentRoleRights"
            default-expand-all
            :props="defaultProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
              <el-button @click="isShowRightDialog = false">取 消</el-button>
              <el-button type="primary" @click="assignRole">确 定</el-button>
            </div>
          </el-dialog>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data () {
    return {
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      isShowAddDialog: false,
      tableData: [],
      isShowEditDialog: false,
      formLabelWidth: '120px',
      editForm: {
        id: '',
        roleName: '',
        roleDesc: ''
      },
      editFormRules: {
        roleName: { required: true, message: '角色名称不能为空', trigger: ['blur', 'change'] },
        roleDesc: { required: true, message: '角色描述不能为空', trigger: ['blur', 'change'] }
      },
      roleId: null,
      allRights: [],
      currentRoleRights: [],
      isShowRightDialog: false,
      defaultProps: {
        children: 'children',
        label: 'authName'
      }
    }
  },
  methods: {
    getRoleList () {
      this.$axios({
        method: 'get',
        url: 'roles'
      }).then(res => {
        // console.log(res)
        this.tableData = res.data
      })
    },
    async addRoles () {
      try {
        let { meta } = await this.$axios.post('roles', this.addForm)
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          this.getRoleList()
          this.isShowAddDialog = false
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    handleClose (row, rightId) {
      console.log(row.id, rightId)
      this.$axios({
        method: 'delete',
        url: `roles/${row.id}/rights/${rightId}`
      }).then(res => {
        const { status, msg } = res.meta
        if (status === 200) {
          this.$message.success(msg)
          console.log(res.data)
          row.children = res.data
        } else {
          this.$message.error(msg)
        }
      })
    },
    async showEditDialog (row) {
      let res = await this.$axios.get(`roles/${row.id}`)
      let { roleId, roleName, roleDesc } = res.data
      this.editForm.id = roleId
      this.editForm.roleName = roleName
      this.editForm.roleDesc = roleDesc
      this.isShowEditDialog = true
    },
    async editRoles () {
      let res = await this.$axios.put(`roles/${this.editForm.id}`, this.editForm)
      console.log(res)
      if (res.meta.status === 200) {
        this.getRoleList()
        this.$message.success('修改成功')
      }
      this.isShowEditDialog = false
    },
    async del (row) {
      try {
        await this.$confirm('你确定要删除改角色吗？？', '温馨提示', {
          configButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await this.$axios.delete('roles/' + row.id)
        if (res.meta.status === 200) {
          this.getRoleList()
          this.$message.success(res.meta.msg)
        } else {
          this.$message.error('删除失败')
        }
      } catch (e) {
        this.$message.info('已取消删除')
      }
    },
    async showRightDialog (row) {
      console.log(row)
      this.roleId = row.id
      console.log(this.roleId)
      let res = await this.$axios.get('rights/tree')
      this.allRights = res.data
      this.currentRoleRights = []
      row.children.forEach(item1 => {
        // this.currentRoleRights.push(item1.id)
        item1.children.forEach(item2 => {
          // this.currentRoleRights.push(item2.id)
          item2.children.forEach(item3 => {
            this.currentRoleRights.push(item3.id)
          })
        })
      })
      // console.log(row, '------------', this.currentRoleRights)
      this.isShowRightDialog = true
    },
    async assignRole () {
      // console.log(row)
      let rids = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()].join()
      console.log(rids)
      try {
        let res = await this.$axios({
          method: 'post',
          url: `roles/${this.roleId}/rights`,
          data: { rids }
        })
        console.log('res', res, this.currentRoleRights)
        if (res.meta.status === 200) {
          this.getRoleList()
          this.$message.success(res.meta.msg)
        } else {
          this.$message.error(res.meta.msg)
        }
      } catch (e) {
        this.$message.error('分配权限失败')
      }
      this.isShowRightDialog = false
    }
  },
  created () {
    this.getRoleList()
  }
}
</script>

<style lang="scss" scoped>
  .el-breadcrumb{
    height: 30px;
    line-height: 30px;
  }
  .el-button{
    margin-top: 10px
  }
  .el-table{
    margin-top: 10px
  }
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .el-tag{
    margin: 10px
  }
  .border-bottom{
    border-bottom: 1px solid #ccc
  }
</style>
